package com.pzhu.listener;

import com.pzhu.controller.UserController;
import com.pzhu.controller.impl.UserControllerImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.*;
import java.util.ArrayList;
import java.util.List;

public class UserCountListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
    ServletContext application = null;
    private UserController userController = new UserControllerImpl();
    public void contextDestroyed(ServletContextEvent event) {
        System.out.println("服务器关闭");
        long loginCount = (long) application.getAttribute("loginCount");
        userController.setLoginCount(loginCount);
    }

    public void contextInitialized(ServletContextEvent event) {
        List<String> list = new ArrayList<String>();
        long loginCount = userController.selectLoginCount();
        System.out.println("启动服务器 ————累计访问人数："+loginCount);
        //用来保存所有已登录的用户
        application = event.getServletContext();
        //取得application对象
        application.setAttribute("loginCount",loginCount );
        application.setAttribute("allUserList", list);
        application.setAttribute("allUserCount", list.size());
        //将集合设置到application范围属性中去
    }

    public void attributeAdded(HttpSessionBindingEvent se) {


        List<String> list = (List<String>) application.getAttribute("allUserList");
        //假设：用户登陆成功之后，只将户名设置到session中
        HttpSession session = se.getSession();
        String userName = (String) session.getAttribute("Uname");
        //取得用户名
        if (!list.contains(userName)&&userName!=null) {
            //表示此用户之前没有登陆
            list.add(userName);
            System.out.println("用户加一");
            long loginCount = (long) application.getAttribute("loginCount");
            application.setAttribute("loginCount",loginCount+1);
            application.setAttribute("allUserList", list);
            application.setAttribute("allUserCount", list.size());
            for (String s:
                 list) {
                System.out.println(s);
            }
        }
    }

    public void attributeRemoved(HttpSessionBindingEvent se) {
        List<String> list = (List<String>) application.getAttribute("allUserList");
        HttpSession session = se.getSession();
        String userName = (String) session.getAttribute("Uname");
        list.remove(userName);
        application.setAttribute("allUserList", list);
        application.setAttribute("allUserCount",  list.size());
    }

    public void attributeReplaced(HttpSessionBindingEvent se) {

    }

    public void sessionCreated(HttpSessionEvent event) {

    }

    public void sessionDestroyed(HttpSessionEvent event) {

    }
}